#include <iostream>
#include <cstdio>
#include <bitset>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN(1E5 + 5);
const int MAXA(1E6 + 5);
struct node {
    int num;
    int beginp;
    int endp;
}dp[MAXN];
bool cmp(node x, node y) {
    if(x.num != y.num) return x.num > y.num;
    else return x.beginp < y.beginp;
}
int vis[MAXA], a[MAXN];
bitset<MAXN> c;
int main() {
    //freopen("color.in", "r", stdin);
    //freopen("color.out", "w", stdout);
    int t;
    cin >> t;
    while(t--) {
        c.reset();
        memset(vis, 0, sizeof vis);
        int n, ans = 0, len = 0;
        cin >> n;
        a[0] = 0;
        for (int i = 1; i <= n; i++) {
            cin >> a[i];
            if(vis[a[i]]) {
                dp[++len].num = a[i];
                dp[len].beginp = vis[a[i]];
                dp[len].endp = i;
                vis[a[i]] = i;
            } else vis[a[i]] = i;
        }
        sort(dp, dp + len, cmp);
        int l = dp[1].beginp, r = dp[1].endp;
        c[l] = c[r] = true;
        for (int i = 2; i <= len; i++) {
            if (dp[i].endp < l && dp[i].beginp >= r) c[dp[i].beginp] = c[dp[i].endp] = 1;
        }
        int red = 0, blue = 0;
        for (int i = 1; i <= n; i++) {
            if (!c[i]) {
                if (a[i] == red) ans += red;
                red = a[i];
            } else if (c[i]) {
                if (a[i] == blue) ans += blue;
                blue = a[i];
            }
        }
        cout << ans << '\n';
    }
    return 0;
}
